﻿using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace NightPlayer
{
    [Activity(Label = "@string/app_name", 
        Theme = "@style/AppTheme", 
        MainLauncher = true, 
        Exported = true, 
        LaunchMode = Android.Content.PM.LaunchMode.SingleTop, 
        ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait,
        Name = "com.zyfdroid.nightplayer.LauncherActivity"
        )]
    [MetaData("android.app.shortcuts", Resource = "@xml/shortcuts")]
    public class LauncherActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            if(PlayerService.player != null)
            {
                StartActivity(new Intent(this,typeof(MainActivity)));
                Finish();
                return;
            }
            SetContentView(Resource.Layout.splash);
            Window.SetNavigationBarColor(Android.Graphics.Color.Black);
            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                if (CheckSelfPermission(Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted)
                {
                    ShowPrivacyDialog();
                }
                else {
                    runBegin();
                }
            }
            else {
                runBegin();
            }
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == 0) {
                if (grantResults[0] == Permission.Granted)
                {
                    runBegin();
                }
                else
                {
                    RunOnUiThread(() => warn("获取音乐列表失败。请检查存储权限"));
                   
                }
            }
        }


        public const string AUDIODIR = "exaudio00004";
        ISharedPreferences SharedPreferences => GetSharedPreferences("main", FileCreationMode.Private);

        public string PrefMusicRoot
        {
            get => SharedPreferences.GetString("musicroot", "MP3");
            set => SharedPreferences.Edit().PutString("musicroot", value).Apply();
        }

        public bool PrefInited
        {
            get => SharedPreferences.GetBoolean("inited", false);
            set => SharedPreferences.Edit().PutBoolean("inited", value).Apply();
        }


        void ensureFileExists() {
            Java.IO.File f = new Java.IO.File(FilesDir, AUDIODIR);
            if (!f.Exists()) { f.Mkdirs(); }
            Assets.List("").Where(a => a.EndsWith(".ogg")).ToList().ForEach(f2 =>
            {
                Android.Util.Log.Warn("extracting assets", f2);
                String destpath = Path.Combine(f.AbsolutePath, f2);
                if (!File.Exists(destpath))
                {
                    using (FileStream fs = File.Open(destpath + ".tmp", FileMode.Create))
                    {
                        using (Stream ins = Assets.Open(f2))
                        {
                            ins.CopyTo(fs);
                        }
                    }
                    File.Move(destpath + ".tmp", destpath);
                }
            });

            Dictionary<string,string> namemapping = new Dictionary<string, string>();
            namemapping.Add("noise_white.ogg", "01 - 白噪音.nof");
            namemapping.Add("noise_pink.ogg", "02 - 粉噪音.nof");
            namemapping.Add("noise_brown.ogg", "03 - 褐噪音.nof");
            namemapping.Add("rain.ogg", "04 - 雨.nof");
            namemapping.Add("riverside.ogg", "05 - 河边.nof");
            namemapping.Add("summer.ogg", "06 - 夏夜.nof");
            namemapping.Add("wave.ogg", "07 - 海浪.nof");

            foreach (KeyValuePair<string, string> entry in namemapping) {
                if (!File.Exists(Path.Combine(f.AbsolutePath, entry.Value)))
                {
                    File.Copy(Path.Combine(f.AbsolutePath, entry.Key), Path.Combine(f.AbsolutePath, entry.Value));
                }
            }
            
        }

        void warn(String text) {
            new AlertDialog.Builder(this).SetCancelable(false).SetMessage(text).SetPositiveButton("退出", new EventHandler<DialogClickEventArgs>((sender, e) => Finish()))
                .Create().Show();
         
        }

        void ShowMusicRootSelection()
        {
            AlertDialog dialog = null; ;
            string[] dirs = Directory.EnumerateDirectories(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath)
                .Where(dir => !dir.StartsWith(".")).Select(d => Path.GetFileName(d)).ToArray();
            Array.Sort(dirs, StringComparer.OrdinalIgnoreCase);
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
            builder.SetTitle("选择一个音乐文件夹：");
            builder.SetItems(dirs, (sender, e) =>
            {
                PrefMusicRoot = dirs[e.Which];
                PrefInited = true;
                dialog?.Dismiss();
                runBegin();
            });
            builder.SetCancelable(false);
            builder.SetPositiveButton("使用 /MP3", (sender, e) =>
            {
                PrefMusicRoot = "MP3";
                PrefInited = true;
                dialog?.Dismiss();
                runBegin();
            });
            dialog = builder.Show();
        }

        void ShowPrivacyDialog()
        {
            string privacyMsg = @"隐私协议：
- 本软件不包含服务端，也没有内置第三方统计服务等。不会上传任何信息。
权限说明：
- 读取内部存储：用于播放音乐文件
- 写入内部存储：用于保存收藏列表
- 启动前台服务：用于创建音乐播放服务
- 保持CPU运行（保持唤醒）：使锁屏后音乐不会停止播放";
            AlertDialog dialog = null;
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
            builder.SetTitle("隐私协议与权限说明：");
            builder.SetMessage(privacyMsg);
            builder.SetPositiveButton("同意并继续", (sender, e) =>
            {
                RequestPermissions(new string[] { Manifest.Permission.WriteExternalStorage }, 0);
                dialog.Dismiss();
            });
            builder.SetNegativeButton("不同意", (sender, e) =>
            {
                Android.Net.Uri uri = Android.Net.Uri.FromParts("package", Application.PackageName, null);
                Intent intent = new Intent(Intent.ActionDelete,uri);
                StartActivity(intent);
                Finish();
                dialog.Dismiss();
            });
            builder.SetCancelable(false);
            dialog = builder.Show();
        }

        void runBegin() {
            if (!PrefInited)
            {
                ShowMusicRootSelection();
                return;
            }

            var slot = Intent.GetStringExtra("slot");
            if (!string.IsNullOrEmpty(slot))
            {
                PlayerService.prefslot = slot;
            }

            new Thread(delegate ()
            {
                ensureFileExists();
                Log.Info("MusicInit","BeginInit");
                if (PlayerService.playlist == null)
                {
                    Java.IO.File f = FilesDir;
                    if (!f.Exists()) { f.Mkdirs(); }
                    f = new Java.IO.File(f, PlayerService.prefslot);
                    if (!f.Exists()) { f.Mkdirs(); }

                    Log.Info("MusicInit", "BeginInit2");
                    Log.Info("MusicInit", "BeginInit3: "+PrefMusicRoot);
                    PlayerService.playlist = new FantasticMusicPlayer.CurrentDirectorySongProvider(PrefMusicRoot,new Java.IO.File(f,"point.conf").AbsolutePath);

                    Log.Info("MusicInit", "BeginInit3");
                    if (PlayerService.playlist.PlayLists == null ||  PlayerService.playlist.PlayLists.Count == 0)
                    {
                        PlayerService.playlist = null; 
                        PrefInited = false;
                        RunOnUiThread(() =>warn("在 内部存储/"+PrefMusicRoot+" 文件夹中没有找到音乐，请创建这个文件夹，并将音乐复制到这个文件夹"));
                        return;
                    }
                    PlayerService.playlist.loadProgress();
                    RunOnUiThread(() => StartService(new Intent(this, typeof(PlayerService))));
                    while (PlayerService.player == null)
                    {
                        Thread.Sleep(300);
                    }
                }
                else
                {
                    Thread.Sleep(300);
                }



                Thread.Sleep(300);
                RunOnUiThread(() => StartActivity(new Intent(this, typeof(MainActivity))));
                RunOnUiThread(() => Finish());
            }).Start();
        }
    }
}